import React, { useEffect, useRef, useState } from 'react'
import { Button, Divider, Dropdown, Form, Input, Select, Space } from 'antd';
import './AddComputedField.less'
import { FIELD_TYPE_OPTIONS } from '@/constant/icons';
import FieldSelect from '../../common/FieldSelect';
import { EditableText } from '../../common/RichText';
import { pick } from 'lodash-es';

export const AddComputedField = ({ onClose }) => {
  const [form] = Form.useForm();
  const initialValues = {
    fieldName: '',
    fieldType: FIELD_TYPE_OPTIONS?.[0]?.value,
    fieldExpression: ''
  }
  const inputRef = useRef(null);

  const addField = (item) => {
    // if (inputRef.current) {
    //   debugger
    //   const { selectionStart, selectionEnd } = inputRef.current?.resizableTextArea?.textArea;
    //   alert(`光标位置: ${selectionStart} 到 ${selectionEnd}`);
    // }
    // debugger
    // const fieldExpression = form.getFieldValue('fieldExpression')
    // form.setFieldsValue({
    //   fieldExpression: `${fieldExpression} ${item.label}`
    // })
    inputRef.current?.insertSpecialTextAtCursor(item.label,pick(item, ['value', 'label']))
    // const { selectionStart, selectionEnd } = inputRef.current?.resizableTextArea?.textArea;
  }

  const addFunction = (item) => {
    const fieldExpression = form.getFieldValue('fieldExpression')
    form.setFieldsValue({
      fieldExpression: `${fieldExpression} ${item.label}`
    })
  }

  const getCursorPosition = () => {
    if (inputRef.current) {
      const { selectionStart, selectionEnd } = inputRef.current.input;
      alert(`光标位置: ${selectionStart} 到 ${selectionEnd}`);
    }
  };

  useEffect(() => {

  }, [])

  const handleSubmit = (value) => {
    debugger
    updateFormValues(value)
    onClose?.()
  }

  return <div className='add-computed-container'>
    <div className='add-computed-body'>
      <Form
        // {...formItemLayout}
        form={form}
        initialValues={initialValues}
        name='starter'
        // layout='vertical'
        style={{
          width: '100%',
          overflowY: 'auto',
          overflowX: 'hidden'
        }}
        onFinish={handleSubmit}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <Form.Item label='字段名称' name='fieldName'
            style={{ flex: 5 }} labelCol={{ span: 3 }}
            rules={[
              {
                required: true,
                message: '请输入字段名称',
                validator: (_, value) => {
                  if (!value) {
                    return Promise.reject(new Error('请输入字段名称'));
                  }
                  if (value.length > 20) {
                    return Promise.reject(new Error('字段名称不能超过20个字符'));
                  }
                  return Promise.resolve();
                }
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item name='fieldType' style={{ flex: 1 }}>
            <Select
              options={FIELD_TYPE_OPTIONS}
              optionRender={(item) => (
                <div>{item?.data?.icon} {item?.label}</div>
              )}
            />
          </Form.Item>
        </div>
        <div style={{ display: 'flex', gap: '16px' }}>
          <Form.Item label='点击引用字段' style={{ flex: 1 }}>
            <FieldSelect options={FIELD_TYPE_OPTIONS}
              style={{ border: 'solid 1px #ccc', padding: 3, borderRadius: 8 }}
              bodyStyle={{ height: 300, overflow: 'auto' }}
              onClick={addField}
            />
          </Form.Item>
          <Form.Item label='点击引用函数' style={{ flex: 1 }}>
            <FieldSelect options={FIELD_TYPE_OPTIONS}
              style={{ border: 'solid 1px #ccc', padding: 3, borderRadius: 8 }}
              bodyStyle={{ height: 300, overflow: 'auto' }}
              onClick={addFunction}
            />
          </Form.Item>
        </div>
        {/* <Form.Item label='字段表达式' name='fieldExpression'>
          <Input.TextArea rows={5} ref={inputRef} />
        </Form.Item> */}
        <Form.Item label='字段表达式' name='fieldExpression'>
          <EditableText  ref={inputRef}/>
        </Form.Item>


        <Divider />
        <div className='add-computed-footer'>
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button type='primary' htmlType='submit'>确定</Button>
          </Space>
        </div>
      </Form>
    </div>
  </div>
}